using System;
using System.IO;


namespace mp3
{
	/// <summary>
	/// Summary description for mp3info.
	/// </summary>
	public class Mp3info
	{
		public long length; // in milliseconds

        public ID3v1 id3v1;
        public ID3v2 id3v2;
		public MPEG mpeg;

        public bool hasID3v1;
        public bool hasID3v2;

        // private contructor
		private Mp3info(){}


        public static Mp3info getFileProperties(string file)
		{
            Mp3info mp3info = new Mp3info();

            if (file.Equals(String.Empty))
			    return null;

            mp3info.id3v1 = ReadID3v1(file);
            mp3info.hasID3v1 = mp3info.id3v1.hasTag;
            mp3info.id3v2 = ReadID3v2(file);
            mp3info.hasID3v2 = mp3info.id3v2.hasTag;
            mp3info.mpeg = ReadMPEG(file);
            mp3info.length = CalculateLength(file, mp3info.mpeg, mp3info.hasID3v1);

            return mp3info;
		}

		private static long CalculateLength(string file, MPEG mpeg, bool hasID3v1)
		{
			FileInfo fi = new FileInfo(file);
            long fileSize = fi.Length;
            long length = 0;
			mpeg.audioBytes = fileSize - mpeg.headerPosition;
			try
			{
				int bitrate = System.Convert.ToInt32(mpeg.Bitrate);
				if (bitrate > 0)
				{
                    if (hasID3v1)
					{
						length = ((mpeg.audioBytes - 128 )* 8) / (bitrate);
					} 
					else 
					{
                        length = (mpeg.audioBytes * 8) / (bitrate);
					}
				}

			}
			catch (Exception e)
			{
                length = 0;
			}

            return length;
		}

        private static ID3v1 ReadID3v1(string file)
		{
			// read id3 stuff
            ID3v1 id3v1 = new ID3v1(file);
			id3v1.Read();
            return id3v1;
		}

        private static ID3v2 ReadID3v2(string file)
		{
			// read id3 stuff
            ID3v2 id3v2 = new ID3v2(file);
			id3v2.Read();
            return id3v2;
		}

        private static MPEG ReadMPEG(string file)
		{
			// read id3 stuff
            MPEG mpeg = new MPEG(file);
			mpeg.Read();
            return mpeg;
		}

	}
}
